from django.shortcuts import render
from django.views import View

# 导入序列化器
from .serializers import *


# Create your views here.
class BarsDoLoginViewSet(viewsets.ModelViewSet):
    __title__ = "PC端员工登录"
    __group__ = "场所直连"
    __info__ = {"post": "PC端员工登录"}
    __doc__ = """
    create:
    <h4>PC端员工登录</h4>
    `登录成功后header中写入:`
        header = {
            "HTTP_HTTPPLACEID":"场所ID",
            "HTTP_HTTPSTAFFID":"员工原始ID"}
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = BarsDoLoginSerializer
    queryset = AllinpayStaffList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # ...提取数据...
        username = serializer.data.get("username")
        barcode = serializer.data.get("password")
        # ...查找用户...
        try:
            Staff = self.get_queryset().get(phone=username)
        except BaseException as err:
            raise serializers.ValidationError({"username": "员工不存在"})
        # ...验证属性...
        if not Staff.status:
            raise serializers.ValidationError({"username": "账户已锁定，请联系管理员。"})
        # ...验证方式 短信...
        if not settings.DEBUG:
            code = REDIS.redis_get("sems", Staff.phone, "code")
            if not code or not barcode == code:
                raise serializers.ValidationError({"password": "验证码不能匹配"})
        REDIS.redis_del("sems", Staff.phone)  # 清除短信缓存
        # 检测门店是否允许登录

        # 创建token
        token = get_tokens_for_user(Staff)
        # 记录登录时间
        Staff.modifed = timezone.now()
        Staff.save()
        return Response({"rescode": 200, "resmsg": token["access"], "staff": Staff.id})


class BarsPlaceInfoViewSet(viewsets.ModelViewSet):
    __title__ = "场所信息"
    __group__ = "场所直连"
    __info__ = {"get": "PC端查询场所信息"}
    __doc__ = """
    list:
    <h4>场所信息列表</h4>
    retrieve:
    <h4>场所信息详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [BarJWTAuthentication]
    permission_classes = [AllPermissions | BarPermissions]
    serializer_class = BarsPlaceInfoSerializer
    queryset = AllinpayPlaceList.objects.all()

    # filter_backends = [ListDjangoFilterBackend]
    # filterset_fields = ['pid', 'intetype']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        # pk = kwargs.get("pk")
        # if not int(pk) == request.placeID:
        #     raise serializers.ValidationError({"Place": "当前场所错误,获取数据失败"})
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class BarsPlaceStaffViewSet(viewsets.ModelViewSet):
    __title__ = "场所员工"
    __group__ = "场所直连"
    __info__ = {"get": "查询场所员工"}
    __doc__ = """
    list:
    <h4>场所员工列表</h4>
    retrieve:
    <h4>场所员工详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [BarJWTAuthentication]
    permission_classes = [AllPermissions | BarPermissions]
    serializer_class = BarsPlaceStaffSerializer
    queryset = AllinpayPlacestaffList.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "sid", "status"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class BarsPlaceStaffPostViewSet(viewsets.ModelViewSet):
    __title__ = "员工在岗离岗"
    __group__ = "场所直连"
    __info__ = {"get": "查询员工在岗", "put": "编辑员工在岗"}
    __doc__ = """
    list:
    <h4>列表员工在岗</h4>
    retrieve:
    <h4>详情员工在岗</h4>
    update:
    <h4>编辑员工在岗</h4>
        员工绑定ID
    """
    http_method_names = ["put"]
    authentication_classes = [BarJWTAuthentication, WeChatJWTAuthentication]
    permission_classes = [BarPermissions | WeChatPermissions]
    serializer_class = BarsPlaceStaffPostSerializer
    queryset = AllinpayPlacestaffPost.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        pk = kwargs.get("pk")
        partial = True
        try:
            instance = self.get_object()
            data = request.data.copy()
            data["current"] = timezone.now()
            serializer = self.get_serializer(instance, data=data, partial=partial)
        except BaseException as err:
            serializer = self.get_serializer(data={"id": pk})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息通知
        from MoniterManager.tasks import doPostEvent

        res = doPostEvent.apply_async((pk,))
        return Response({"rescode": 200, "resmsg": serializer.data})


class ThisBarsPlaceStaffPostViewSet(viewsets.ModelViewSet):
    __title__ = "自己在岗离岗"
    __group__ = "场所直连"
    __info__ = {"post": "编辑自己在岗离岗"}
    __doc__ = """
    create:
    <h4>编辑自己在岗离岗</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [BarJWTAuthentication, WeChatJWTAuthentication]
    permission_classes = [BarPermissions | WeChatPermissions]
    serializer_class = ThisBarsPlaceStaffPostSerializer
    queryset = AllinpayPlacestaffPost.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            bind = AllinpayPlacestaffList.objects.get(
                pid=serializer.data.get("pid"), sid=request.user.id, status=1
            )
            load = REDIS.redis_hash_key("loginPlace", request.user.id)
        except BaseException as err:
            raise serializers.ValidationError({"PlaceStaff": "编辑失败，当前员工已离职"})
        else:
            # if not request.user.id == bind.sid:
            #     raise serializers.ValidationError({"login": "禁止编辑，当前员工未登录"})
            if not int(load) == serializer.data.get("pid"):
                raise serializers.ValidationError({"login": "禁止编辑，当前员工未登录该场所"})

        r, faq = AllinpayPlacestaffPost.objects.update_or_create(
            defaults={
                "status": serializer.data.get("status"),
                "current": timezone.now(),
            },
            id=bind.id,
        )

        # 发送消息通知
        from MoniterManager.tasks import doPostEvent

        res = doPostEvent.apply_async((r.id,))

        return Response({"rescode": 200, "resmsg": serializer.data})


# 检查视图
filter_views(globals())
